package com.upcode.weighing.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.upcode.weighing.base.controller.BaseController;
import com.upcode.weighing.common.Constants;
import com.upcode.weighing.common.exception.FileServerException;
import com.upcode.weighing.config.FileServerConfig;
import com.upcode.weighing.contant.FileContant;
import com.upcode.weighing.domain.SysFile;
import com.upcode.weighing.service.SysFileService;
import com.upcode.weighing.utils.HttpUtils;
import com.upcode.weighing.utils.MyX509TrustManager;
import com.upcode.weighing.vo.resp.BaseResponseVo;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.net.ssl.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 文件信息表 前端控制器
 * </p>
 *
 * @author ZYW
 * @since 2018-04-06
 */
@RestController
@RequestMapping("/file")
public class SysFileController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(SysFileController.class);
    @Autowired
    private SysFileService sysFileService;

    @Autowired
    private FileServerConfig fileServerConfig;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${gaode.key}")
    private String key;

    @PostMapping(value = "/upload")
    public ResponseEntity<BaseResponseVo<ImmutableMap<String, String>>> upload(@RequestParam(value = "file", required = false) MultipartFile file) {
        Long sysFileId = this.procUploadFile(file, null);
        if (sysFileId != null) {
            return HttpResponse.success(ImmutableMap.of("id", String.valueOf(sysFileId)));
        }
        return HttpResponse.error(null);
    }

    /**
     * 上传检测视频
     *
     * @param detectId 检测id,在检测开始时由便携机传给无人机
     */
    @PostMapping(value = "/vedioupload/{detectId}")
    public Object vedioUpload(@PathVariable("detectId") String detectId, @RequestParam(value = "file", required = false) MultipartFile file) {
        if (StringUtils.isEmpty(detectId)) {
            throw new FileServerException("检测id为空！");
        }

        Long sysFileId = this.procUploadFile(file, null);//视频文件id
        if (sysFileId != null) {
            return HttpResponse.success();
        } else {
            return HttpResponse.error();
        }
    }

    @PostMapping(value = "/auditUpload")
    public Object auditUpload(@RequestParam(value = "file", required = false) MultipartFile file) {
        Long sysFileId = this.procUploadFile(file, null);
        if (sysFileId != null) {
            return success(ImmutableMap.of("id", String.valueOf(sysFileId)), "上传成功！");
        }
        return error("上传失败！");
    }

    @PostMapping(value = "/uploadV2")
    @CrossOrigin(origins = "*", allowedHeaders = "*", maxAge = 3600)
    public Object uploadV2(@RequestParam(value = "file", required = false) MultipartFile file) {
        Long sysFileId = this.procUploadFile(file, null);
        if (sysFileId != null) {
            // 返回成功信息
            ImmutableMap<String, String> dataMap = ImmutableMap.of("id", String.valueOf(sysFileId));
            Map<String, Object> map = Maps.newHashMap();
            map.put("code", 200);
            map.put("data", dataMap);
            map.put("msg", "上传成功！");
            map.put("timestamp", System.currentTimeMillis());
            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(map);
        }

        // 返回错误信息
        Map<String, Object> map = Maps.newHashMap();
        map.put("code", 400);
        map.put("msg", "上传失败！");
        map.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body(map);
    }

    /**
     * convertPdf
     *
     * @param file       上传文件
     * @param convertPdf 需要转换pdf
     * @return
     */
    private Long procUploadFile(MultipartFile file, Boolean convertPdf) {
        if (file == null || file.isEmpty()) {
            throw new FileServerException("上传文件File为空！");
        }

        DateTime now = DateTime.now();
        String uploadFolder = now.toString(Constants.YYYYMMdd);

        String path = fileServerConfig.getPath();

        if (StringUtils.endsWith(path, Constants.PATH_SEPARATOR_LINUX)
                || StringUtils.endsWith(path, Constants.PATH_SEPARATOR_WIN)) {
            path = path + uploadFolder;
        } else {
            path = path + File.separator + uploadFolder;
        }

        File pathFile = new File(path);
        if (!pathFile.exists() && !pathFile.mkdirs()) {
            throw new FileServerException("创建文件夹失败！");
        }

        String origName = file.getOriginalFilename();
        String extName = FilenameUtils.getExtension(origName);
        String newFileName = now.toString(Constants.YYYYMMddHHmmssSSS) + "." + extName;
        long size = file.getSize();

        try {
            String destFilePath = pathFile + File.separator + newFileName;
            logger.debug("上传文件路径:[{}]", destFilePath);
            file.transferTo(new File(destFilePath));
        } catch (IOException e) {
            logger.error("上传文件File为空！", e);
            throw new FileServerException("上传文件File为空！", e);
        }

        SysFile sysFile = new SysFile();
        sysFile.setExt(extName);
        sysFile.setOrigName(origName);
        sysFile.setName(newFileName);
        sysFile.setPath(uploadFolder);//改用相对路径
        sysFile.setSize(size);
        boolean result = sysFileService.save(sysFile);
        if (result) {
            if (ObjectUtil.isNotNull(convertPdf) && convertPdf) {
                if (StringUtils.equals(extName, FileContant.FILE_SUFFIX_DOC) || StringUtils.equals(extName, FileContant.FILE_SUFFIX_DOCX)) {
                    try {
                        sysFileService.docConverter(sysFile);
                    } catch (Exception e) {
                        logger.error("转换文件失败 ！", e);
                        logger.info("转换文件失败 - 原因： {}", e.getMessage());
                    }
                }
            }
            return sysFile.getId();
        } else {
            return null;
        }
    }

    @PostMapping(value = "/uploads")
    public Object uploads(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                .getFiles("files");
        if (CollectionUtils.isEmpty(files)) {
            throw new FileServerException("上传文件为空！");
        }

        DateTime now = DateTime.now();
        String uploadFolder = now.toString(Constants.YYYYMMdd);

        String path = fileServerConfig.getPath();

        if (StringUtils.endsWith(path, Constants.PATH_SEPARATOR_LINUX)
                || StringUtils.endsWith(path, Constants.PATH_SEPARATOR_WIN)) {
            path = path + uploadFolder;
        } else {
            path = path + File.separator + uploadFolder;
        }

        File pathFile = new File(path);
        if (!pathFile.exists() && !pathFile.mkdirs()) {
            throw new FileServerException("创建文件夹失败！");
        }

        List<SysFile> sysFileList = Lists.newArrayList();
        SysFile sysFile = null;

        for (MultipartFile file : files) {
            String origName = file.getOriginalFilename();
            String extName = FilenameUtils.getExtension(origName);
            String newFileName = IdWorker.getIdStr() + "." + extName;
            long size = file.getSize();

            try {
                file.transferTo(new File(pathFile + File.separator + newFileName));
            } catch (IOException e) {
                throw new FileServerException("上传文件File为空！", e);
            }

            sysFile = new SysFile();
            sysFile.setId(IdWorker.getId());
            sysFile.setExt(extName);
            sysFile.setOrigName(origName);
            sysFile.setName(newFileName);
            sysFile.setPath(uploadFolder);
            sysFile.setSize(size);
            sysFile.setStatus(Constants.STATUS_NORMAL);
            sysFileList.add(sysFile);
        }

        boolean result = sysFileService.saveBatch(sysFileList);
        if (result) {
            List<String> ids = sysFileList.stream().map(item -> String.valueOf(item.getId())).collect(Collectors.toList());
            return success(ImmutableMap.of("id", Joiner.on(",").join(ids)), "上传成功！");
        }
        return error("上传失败！");
    }

    @ApiOperation(value = "多附件上传接口（最多5张）", notes = "")
    @PostMapping(value = "/uploadFiles")
    public Object uploadFiles(@RequestParam(value = "files", required = false) MultipartFile[] files) {
        logger.debug("开始请求多附件上传接口");
        try {
            if (null == files || files.length == 0) {
                return error("请至少选择一个图片");
            }
            if (files.length > 5) {
                return error("最多只能上传5张图片");
            }
            DateTime now = DateTime.now();
            String uploadFolder = now.toString(Constants.YYYYMMdd);
            String path = fileServerConfig.getPath();
            if (StringUtils.endsWith(path, Constants.PATH_SEPARATOR_LINUX)
                    || StringUtils.endsWith(path, Constants.PATH_SEPARATOR_WIN)) {
                path = path + uploadFolder;
            } else {
                path = path + File.separator + uploadFolder;
            }

            File pathFile = new File(path);
            if (!pathFile.exists() && !pathFile.mkdirs()) {
                throw new FileServerException("创建文件夹失败！");
            }
            List<SysFile> sysFileList = Lists.newArrayList();
            List<String> fileIds = new ArrayList<>();
            for (MultipartFile file : files) {
                SysFile sysFile = new SysFile();
                String origName = file.getOriginalFilename();
                String extName = FilenameUtils.getExtension(origName);
                String newFileName = IdWorker.getIdStr() + "." + extName;
                long size = file.getSize();
                logger.debug(String.format("文件[%s]的长度为[%s]", origName, size));
                try {
                    file.transferTo(new File(pathFile + File.separator + newFileName));
                } catch (IOException e) {
                    throw new FileServerException("图片上传异常");
                }
                sysFile.setId(IdWorker.getId());
                sysFile.setExt(extName);
                sysFile.setOrigName(origName);
                sysFile.setName(newFileName);
                sysFile.setPath(uploadFolder);
                sysFile.setSize(size);
                sysFile.setStatus(Constants.STATUS_NORMAL);
                sysFileList.add(sysFile);
                fileIds.add(String.valueOf(sysFile.getId()));
            }
            boolean result = sysFileService.saveBatch(sysFileList);
            if (result) {
                return success(fileIds, "上传成功！");
            }
            return error("上传失败！");
        } catch (Exception e) {
            logger.error(String.format("多附件上传接口异常，异常信息为[%s]", e.getMessage()), e);
            return error("上传失败！");
        }
    }

    @GetMapping("/download/{id}")
    public void downLoadFile(@PathVariable("id") String id, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(id)) {
            throw new FileServerException("文件ID为空！");
        }
        String path = fileServerConfig.getPath();
        SysFile sysFile = sysFileService.getById(id);
        if (sysFile == null) {
            throw new FileServerException(id + "不能查询到文件信息！");
        }
        final String fileName = sysFile.getName();
        final String filePath = sysFile.getPath();
        if (StringUtils.isEmpty(fileName) || StringUtils.isEmpty(filePath)) {
            throw new FileServerException("文件路径或者名称为空！");
        }
        try {
            String downFileName = null;
            // 设置response参数，可以打开下载页面
            response.reset();
            response.setContentType("application/octet-stream");
            boolean isMSIE = HttpUtils.isMSBrowser(request);
            if (isMSIE) {
                //IE浏览器的乱码问题解决
                downFileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                //万能乱码问题解决
                downFileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            }
            response.setHeader("Content-disposition", "attachment;filename=\"" + downFileName + "\"");
            String downloadPath = path + File.separator + filePath + File.separator + fileName;
            File file = new File(downloadPath);
            if (!file.exists()) {
                throw new FileServerException(downloadPath + "文件不存在！");
            }
            logger.debug("文件下载路径为:" + file.toPath());
            Files.copy(file.toPath(), response.getOutputStream());
        } catch (IOException e) {
            throw new FileServerException("下载文件异常！", e);
        }
    }

    @GetMapping("/auditDownload/{id}")
    public void auditDownload(@PathVariable("id") String id, HttpServletResponse response) {
        if (StringUtils.isEmpty(id)) {
            throw new FileServerException("文件ID为空！");
        }
        String path = fileServerConfig.getPath();
        SysFile sysFile = sysFileService.getById(id);
        if (sysFile == null) {
            throw new FileServerException(id + "不能查询到文件信息！");
        }
        final String fileName = sysFile.getName();
        final String filePath = sysFile.getPath();
        if (StringUtils.isEmpty(fileName) || StringUtils.isEmpty(filePath)) {
            throw new FileServerException("文件路径或者名称为空！");
        }
        try {
            // 设置response参数，可以打开下载页面
            response.reset();
            response.setContentType("binary/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String((sysFile.getOrigName()).getBytes(), "iso-8859-1"));
            String downloadPath = path + File.separator + filePath + File.separator + fileName;
            File file = new File(downloadPath);
            if (!file.exists()) {
                throw new FileServerException(downloadPath + "文件不存在！");
            }
            logger.debug("文件下载路径为:" + file.toPath());
            Files.copy(file.toPath(), response.getOutputStream());
        } catch (IOException e) {
            throw new FileServerException("下载文件异常！", e);
        }
    }

    /**
     * 根据fileId得到服务器相对路径，主要配合nginx来实现图片在线显示
     *
     * @param id sys_file 表的主键
     * @return
     */
    @ApiOperation(value = "根据ID获取相对路径", notes = "")
    @GetMapping("/getPath/{id}")
    public Object getPath(@PathVariable("id") String id) {
        if (StringUtils.isEmpty(id)) {
            return error("文件ID为空！");
        }
        String path = fileServerConfig.getPath();
        SysFile sysFile = sysFileService.getById(id);
        if (sysFile == null) {
            return error(id + "不能查询到文件信息！");
        }
        final String fileName = sysFile.getName();
        final String filePath = sysFile.getPath();
        if (StringUtils.isEmpty(fileName) || StringUtils.isEmpty(filePath)) {
            return error("文件路径或者名称为空！");
        }
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("path", filePath + File.separator + fileName);
        return success(resultMap);
    }

    @GetMapping("/ftp/download")
    public void downLoadFtpFile(@RequestParam("name") String name, HttpServletResponse response) {
        if (StringUtils.isEmpty(name)) {
            throw new FileServerException("文件名称为空！");
        }
        String ftpPath = fileServerConfig.getFtpPath();

        if (StringUtils.isEmpty(ftpPath)) {
            throw new FileServerException("配置信息为空！");
        }

        if (!ftpPath.endsWith("/") || !ftpPath.endsWith("\\")) {
            ftpPath += File.separator;
        }

        String filePath = ftpPath + name;

        File file = new File(filePath);
        if (!file.exists()) {
            response.setStatus(HttpStatus.NOT_FOUND.value());
        } else {
            try {
                // 设置response参数，可以打开下载页面
                response.reset();
                response.setContentType("binary/octet-stream;charset=UTF-8");
                response.setHeader("Content-Disposition",
                        "attachment;filename=" + name);
                Files.copy(file.toPath(), response.getOutputStream());
            } catch (IOException e) {
                response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                //throw new FileServerException("下载文件异常！",e);
            }
        }
    }

    public boolean checkFileSize(String path) {
        File idFile = new File(path);
        long fileSize = idFile.length();
        return (fileSize <= 3 * 1024 * 1024);
    }

    public boolean checkFileSize(File file) {
        long fileSize = file.length();
        return (fileSize <= 3 * 1024 * 1024);
    }


    /**
     * 支持https格式 get请求
     *
     * @return 返回json格式
     */
    @ApiOperation(value = "获取行政区域地址", notes = "")
    @PostMapping(value = "/getAddress/{keywords}/{subdistrict}")
    public JSONObject getAddress(@PathVariable("keywords") String keywords,
                                 @PathVariable("subdistrict") String subdistrict) {
        InputStream inStream = null;
        ByteArrayOutputStream outStream = null;
        try {
            String hsUrl = "https://restapi.amap.com/v3/config/district?keywords=" + keywords + "&subdistrict=" +
                    subdistrict + "&key=" + key;
            URL url;
            url = new URL(hsUrl);
            HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, tm, null);

            con.setSSLSocketFactory(ctx.getSocketFactory());
            con.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }
            });


            inStream = con.getInputStream();
            outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            byte[] b = outStream.toByteArray();//网页的二进制数据


            String rtn = new String(b, "utf-8");
            if (org.apache.commons.lang.StringUtils.isNotBlank(rtn)) {
                JSONObject object = JSONObject.parseObject(rtn);
                return object;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return null;
    }

    /*@ApiOperation(value = "APP包上传",notes ="")
    @PostMapping(value = "/uploadAppPack")
    public Object uploadAppPack(@RequestParam(value = "file", required = true) MultipartFile file) {
        try{
            logger.debug("开始上传APP包");
            if (file == null || file.isEmpty()) {
                return error("上传文件File为空！");
            }
            String path = fileServerConfig.getAppPackPath();
            File pathFile = new File(path);
            if (!pathFile.exists() && !pathFile.mkdirs()) {
                return error("创建文件夹失败！");
            }
            String origName = file.getOriginalFilename();
            String extName = FilenameUtils.getExtension(origName);
            if(StringUtils.isEmpty(extName)){
                return error("文件格式不正确");
            }
            List<String> list = new ArrayList<>();
            list.add("apk");
            list.add("ipa");
            if(!list.contains(extName)){
                return error("文件格式不正确");
            }
            DateTime now = DateTime.now();
            String newFileName = now.toString(Constants.YYYYMMddHHmmssSSS) + "." + extName;
            try {
                String destFilePath = pathFile + File.separator + newFileName;
                logger.debug("上传文件路径:[{}]", destFilePath);
                file.transferTo(new File(destFilePath));
            } catch (IOException e) {
                return error("上传文件File为空！");
            }
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("fileName", newFileName);
            resultMap.put("origName", origName);
            resultMap.put("downloadPath", pathFile + File.separator + newFileName);
            resultMap.put("eidtionName", "");
            resultMap.put("eidtionCode", "");
            return success(resultMap,"上传成功");
        }catch (Exception e){
            logger.error(String.format("上传APP包异常,异常信息为[%s]",e.getMessage()),e);
            return error("上传APP包异常");
        }
    }*/

    @ApiOperation(value = "APP包上传(新版本)", notes = "")
    @PostMapping(value = "/uploadAppPack")
    public Object uploadAppPack(@RequestParam(value = "file", required = true) MultipartFile file) {
        try {
            logger.debug("开始上传APP包");
            if (file == null || file.isEmpty()) {
                return error("上传文件File为空！");
            }
            String path = fileServerConfig.getAppPackUploadPath();
            File pathFile = new File(path);
            if (!pathFile.exists() && !pathFile.mkdirs()) {
                return error("创建文件夹失败！");
            }
            String origName = file.getOriginalFilename();
            if (!StringUtils.endsWith(origName, ".apk") && !StringUtils.endsWith(origName, ".ipa")) {
                return error("文件格式不正确");
            }
            String destFilePath = pathFile + File.separator + origName;
            try {
                logger.debug("上传文件路径:[{}]", destFilePath);
                file.transferTo(new File(destFilePath));
            } catch (IOException e) {
                return error("上传文件File为空！");
            }
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("fileName", origName);
            resultMap.put("origName", origName);
            resultMap.put("downloadPath", pathFile + File.separator + origName);
            resultMap.put("eidtionName", "");
            resultMap.put("eidtionCode", "");
            return success(resultMap, "上传成功");
            /*String uploadpath = fileServerConfig.getAppPackUploadPath();
            if(StringUtils.isBlank(uploadpath)){
                return error("请配置上传路径");
            }
            if(StringUtils.isBlank(fileServerConfig.getFtpIp()) || StringUtils.isBlank(fileServerConfig.getFtpUser())
                    || StringUtils.isBlank(fileServerConfig.getFtpPassword()) || fileServerConfig.getFtpPort() != 2222 ){
                return error("上传失败，远程服务器配置错误");
            }
            logger.debug(String.format("配置文件中的远程服务器信息,IP为[%s],端口号为[%s],用户名为[%s],密码为[%s]",
                    fileServerConfig.getFtpIp(),fileServerConfig.getFtpPort(),
                    fileServerConfig.getFtpUser(),fileServerConfig.getFtpPassword()));
            SCPUtil scpUtil = new SCPUtil(fileServerConfig.getFtpIp(),fileServerConfig.getFtpPort(),
                    fileServerConfig.getFtpUser(),fileServerConfig.getFtpPassword());
            String uploadString = scpUtil.putFile(destFilePath,uploadpath);
            if(StringUtils.equals("上传成功",uploadString)){
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("fileName", origName);
                resultMap.put("origName", origName);
                resultMap.put("downloadPath", pathFile + File.separator + origName);
                resultMap.put("eidtionName", "");
                resultMap.put("eidtionCode", "");
                return success(resultMap,"上传成功");
            }
            return error("上传失败");*/
        } catch (Exception e) {
            logger.error(String.format("上传APP包异常,异常信息为[%s]", e.getMessage()), e);
            return error("上传APP包异常");
        }
    }


    @PostMapping(value = "/uploadRoadUserTemplate")
    public Object uploadRoadUserTemplate(@RequestParam(value = "file", required = false) MultipartFile file) {
        String id = fileServerConfig.getTemplateFileId();
        if (file == null || file.isEmpty()) {
            throw new FileServerException("上传文件File为空！");
        }
        DateTime now = DateTime.now();
        String uploadFolder = now.toString(Constants.YYYYMMdd);
        String path = fileServerConfig.getPath();
        if (StringUtils.endsWith(path, Constants.PATH_SEPARATOR_LINUX)
                || StringUtils.endsWith(path, Constants.PATH_SEPARATOR_WIN)) {
            path = path + uploadFolder;
        } else {
            path = path + File.separator + uploadFolder;
        }
        File pathFile = new File(path);
        if (!pathFile.exists() && !pathFile.mkdirs()) {
            throw new FileServerException("创建文件夹失败！");
        }

        String origName = file.getOriginalFilename();
        String extName = FilenameUtils.getExtension(origName);
        String newFileName = now.toString(Constants.YYYYMMddHHmmssSSS) + "." + extName;
        long size = file.getSize();
        try {
            String destFilePath = pathFile + File.separator + newFileName;
            logger.debug("上传文件路径:[{}]", destFilePath);
            file.transferTo(new File(destFilePath));
        } catch (Exception e) {
            logger.error(String.format("上传附件异常，异常信息为[%s]", e.getMessage()), e);
            throw new FileServerException("上传文件File为空！");
        }

        boolean result = false;
        SysFile sysFile = sysFileService.getById(id);
        if (null == sysFile) {
            sysFile = new SysFile();
            sysFile.setId(Long.valueOf(id));
            sysFile.setExt(extName);
            sysFile.setOrigName(origName);
            sysFile.setName(newFileName);
            sysFile.setPath(path);
            sysFile.setSize(size);
            result = sysFileService.save(sysFile);
        } else {
            sysFile.setExt(extName);
            sysFile.setOrigName(origName);
            sysFile.setName(newFileName);
            sysFile.setPath(path);
            sysFile.setSize(size);
            result = sysFileService.updateById(sysFile);
        }
        if (result) {
            return success(ImmutableMap.of("id", String.valueOf(sysFile.getId())), "上传成功！");
        }
        return error("上传失败！");
    }

    @GetMapping("/hello")
    @ApiOperation(value = "测试", notes = "测试")
    public Object hello() {
        logger.debug("hello-测试 admin微服务--");
        logger.info("hello-测试  admin微服务--");
        return success("成功");
    }

    @ApiOperation(value = "预览pdf 和 word", notes = "预览pdf 和 word")
    @RequestMapping("/displayPDF/{fileId}")
    @ResponseBody
    public void displayPDF(@PathVariable Long fileId, HttpServletRequest request, HttpServletResponse response) {
        try {
            // 获取pdf文件
            SysFile pdfFile = sysFileService.findPdfFile(fileId);
            String path = fileServerConfig.getPath();
            final String fileName = pdfFile.getName();
            final String filePath = pdfFile.getPath();
            String downloadPath = path + File.separator + filePath + File.separator + fileName;
            File pdf = new File(downloadPath);
            if (!pdf.exists()) {
                throw new FileServerException(downloadPath + "文件不存在！");
            }
            logger.info("【预览pdf 和 word】 - 文件路劲：{}", downloadPath);
            String downFileName;
            boolean isMSIE = HttpUtils.isMSBrowser(request);
            if (isMSIE) {
                //IE浏览器的乱码问题解决
                downFileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                //万能乱码问题解决
                downFileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            }
            LocalDateTime startTime = LocalDateTime.now();
            FileInputStream fileInputStream = new FileInputStream(pdf);
            response.reset();
            response.setHeader("Content-Disposition", "attachment;fileName=" + downFileName);
            response.setContentType("multipart/form-data");
            OutputStream outputStream = response.getOutputStream();
            IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream);
            LocalDateTime endTime = LocalDateTime.now();
            Duration between = Duration.between(startTime, endTime);
            logger.info("【预览pdf 和 word】 - 开启文件流时间：{} - 关闭文件流时间：{} - 时差：{} 毫秒", startTime, endTime, between.toMillis());
        } catch (Exception e) {
            logger.info("预览文件错误：{}", e.getMessage());
            throw new FileServerException(e.getMessage());
        }
    }
}

